<?php

/**
 * Class for viewing a select element.
 *
 * @author Ian Clarence <ian.clarence@gmail.com>
 */
class ViewSelect extends ViewHtmlFormElement {

    /**
     * The constructor.
     *
     * @param array $fields
     */
    public function __construct(array $fields = array()) {

        $fields["tag"] = "select";
        $fields["data"] = isset($fields["data"]) ? $fields["data"] : array();

        parent::__construct($fields);

        /**
         * Insert an extra option if the select message is set.
         */
        if (isset($this->fields["message"])) {
            $this->addInnerHtml(self::elementInit("option", $this->getMessage(), "value", "0"));
        }
        
        /**
         * Loop over the possible values, creating the options.
         */
        foreach ($this->getData() as $key => $datum) {
            $optionValue = is_array($datum) ? $datum[0] : $datum;
            $option = self::elementInit("option", (is_array($datum) ? $datum[1] : $datum), "value", $optionValue);
            $option->setAttribute("id", $key + 1);
            if ($value == $optionValue) {
                $option->setAttribute("selected", "selected");
            }
            $this->addInnerHtml($option);
        }

    }

}